package com.tanhua.server.service;
import org.bson.types.ObjectId;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.VoiceUser;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.VoiceVo;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.mongo.Voice;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class PeachblossomService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private SoundApi soundApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private UserLikeApi userLikeApi;

    @Reference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 接口名称：桃花传音-发送语音
     */
    public ResponseEntity<Object> saveVoice(MultipartFile soundFile) throws IOException {

        // 语音上传到fastDFS
        String soundFileName = soundFile.getOriginalFilename();
        String substring = soundFileName.substring(soundFileName.lastIndexOf(".") + 1);
        StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(),
                soundFile.getSize(), substring, null);
        String soundUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

        // 保存Voice
        Voice voice = new Voice();

        voice.setUserId(UserHolder.getUserId());
        voice.setSoundUrl(soundUrl);
        voice.setCreated(System.currentTimeMillis());

        //调用服务提供者Api保存Voice
        soundApi.save(voice);

        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：桃花传音-接收语音
     * 接口路径：GET/peachblossom
     */
    public ResponseEntity<Object> receptionVoice() {

        // 获取当前用户的id
        Long userId = UserHolder.getUserId();

        // 查询当前用户的剩余次数
        VoiceUser voiceUser = soundApi.findById(userId);

        if (voiceUser.getRemainingTimes() > 0) {
            // 消耗剩余次数
            Long remainingTimes = voiceUser.getRemainingTimes();
            voiceUser.setRemainingTimes(remainingTimes - 1);

            // 保存更新后的剩余次数
            soundApi.updateVoiceUser(voiceUser);

            // 随机查询一条桃花传音信息
            Voice voice = soundApi.randomFind(userId);
            if (voice == null) {
                // 返回消耗的次数
                voiceUser.setRemainingTimes(voiceUser.getRemainingTimes() + 1);
                // 保存更新后的剩余次数
                soundApi.updateVoiceUser(voiceUser);
                return ResponseEntity.status(500).body(ErrorResult.soundError());
            }

            // 修改reception
            soundApi.update(voice, 0);

            // 封装返回的数据
            VoiceVo vo = new VoiceVo();
            // 获取被接收用户的详情
            UserInfo userInfo = userInfoApi.findById(voice.getUserId());
            if (userInfo != null) {
                BeanUtils.copyProperties(userInfo, vo);
            }

            vo.setId(voice.getUserId().intValue());
            vo.setSoundUrl(voice.getSoundUrl());

            // 封装剩余次数
            vo.setRemainingTimes(voiceUser.getRemainingTimes().intValue());

            return ResponseEntity.ok(vo);
        }

        return ResponseEntity.status(500).body(ErrorResult.remainingTimesError());
    }

    /**
     * 接口名称：桃花传音 - 不喜欢
     */
    public ResponseEntity<Object> unloveSound(Long soundId) {
        return null;
    }
}
